package com.example.starter.pubsub.redis;

import cn.hutool.core.util.ObjUtil;
import com.example.starter.pubsub.api.PubCallback;
import com.example.starter.pubsub.api.PubResult;
import com.example.starter.pubsub.api.PubTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author 王令
 * @since 2023/6/30 11:21
 */
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "com.example.pub-sub", name = "type", havingValue = "redis")
public class RedisPubTemplate implements PubTemplate {

    private final RedisTemplate<String, Object> redisTemplate;


    @Override
    public PubResult syncSend(String topic, Object message) {
        redisTemplate.convertAndSend(topic, message);
        return null;
    }

    @Override
    public void asyncSend(String topic, Object message, PubCallback callback) {
        try {
            redisTemplate.convertAndSend(topic, message);
            if (ObjUtil.isNotNull(callback)) {
                callback.onSuccess(null);
            }
        } catch (Exception e) {
            if (ObjUtil.isNotNull(callback)) {
                callback.onFailure(e);
            }
        }
    }

    @Override
    public void asyncSend(String topic, Object message) {
        redisTemplate.convertAndSend(topic, message);
    }
}
